package net.entelijan.cobean.util;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.UIManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Action listener that opens a message box, and writes the stacktrace to the
 * current logger if an error occurres.
 * 
 */
public abstract class GuiActionListener implements ActionListener {

	private static Log log = LogFactory.getLog(GuiActionListener.class);

	private Component parent;

	public GuiActionListener() {
		super();
	}

	public GuiActionListener(Component parent) {
		this();
		this.parent = parent;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			guiActionPerformed(e);
		} catch (Throwable t) {
			if (isCriticalException(t)) {
				log.warn("Could not perform action because: " + getMessage(t),
						t);
				JOptionPane.showMessageDialog(this.parent, getMessage(t),
						UIManager.getString("OptionPane.messageDialogTitle"),
						JOptionPane.ERROR_MESSAGE);

			} else if (log.isDebugEnabled()) {
				log.debug("Could not perform action because: " + getMessage(t),
						t);
			}
			JOptionPane.showMessageDialog(this.parent, getMessage(t), UIManager
					.getString("OptionPane.messageDialogTitle"),
					JOptionPane.ERROR_MESSAGE);
		}

	}

	private boolean isCriticalException(Throwable t) {
		return (t instanceof NullPointerException || t instanceof Error);
	}

	private String getMessage(Throwable t) {
		String msg = t.getMessage();
		if (msg == null || msg.isEmpty()) {
			msg = t.toString();
		}
		return msg;
	}

	public abstract void guiActionPerformed(ActionEvent e) throws Throwable;

}
